package com.sinosoft.handler;

import com.alibaba.fastjson.JSON;
import com.sinosoft.domain.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @author hyy85
 * @version 1.0
 * @date: 19/6/2018 上午 9:47<br/>
 * @description 全局数据统一输出
 * @since 1.8
 */
public class GlobalMessageConverter extends MappingJackson2HttpMessageConverter {

    private static Logger logger = LoggerFactory.getLogger(GlobalMessageConverter.class);

    @Override
    protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

        if (object instanceof Result) {
            super.writeInternal(object, type, outputMessage);
            return;
        }

        Result<Object> baseRes = new Result<>();
        baseRes.setData(object);
        baseRes.setReturnMsg("成功");
        baseRes.setReturnCode(0);
        logger.info("输出参数：" + JSON.toJSONString(baseRes));
        super.writeInternal(baseRes, Result.class, outputMessage);
    }
}
